from django.http import JsonResponse
from django.views import View

from util.ApiResponse import ApiResponse, success_response
from .services.ProductService import ProductService


class ProductListView(View):

    def get(self, request):
        query = request.GET.get('query', '')  # 获取查询关键字
        page = request.GET.get('page', 1)  # 获取页码，默认第一页
        per_page = request.GET.get('per_page', 10)  # 每页显示的商品数量

        product_service = ProductService()
        # 调用服务层进行商品搜索
        products = product_service.search_products(query, page, per_page)

        response_data = {
            'products': list(products),
            'page': products.number,
            'total_pages': products.paginator.num_pages
        }

        return success_response(response_data)